#include "DisplayManager.h"


DisplayManager::DisplayManager()
{
}

DisplayManager::~DisplayManager()
{
}

DisplayManager* DisplayManager::m_xInstance = nullptr;

DisplayManager* DisplayManager::GetInstance()
{
	if (m_xInstance == nullptr)
	{
		m_xInstance = new DisplayManager;
	}
	return m_xInstance;
}

void DisplayManager::Destroy()
{
	if (m_xInstance != NULL)
	{
		delete m_xInstance;
		m_xInstance = NULL;
	}
}


void DisplayManager::Initialize()
{
	m_xWindow = new sf::RenderWindow(sf::VideoMode(1280, 961), "AIProject");
}

sf::RenderWindow* DisplayManager::GetRenderWindow()
{
	return m_xWindow;
}

void DisplayManager::AddDrawable(sf::Drawable* p_Sprite, unsigned int p_DrawPriority)
{
	Drawables drawable;
	drawable.m_xSprite = p_Sprite;
	drawable.m_iDrawOrder = p_DrawPriority;

	for (unsigned int i = 0; i < m_xDrawable.size(); i++)
	{
		if (m_xDrawable[i].m_xSprite == p_Sprite)
		{
			std::cout << "sprite already exist" << std::endl;
			return;
		}
	}

	for (unsigned int i = 0; i < m_xDrawable.size(); i++)
	{
		if (m_xDrawable[i].m_iDrawOrder > drawable.m_iDrawOrder)
		{
			if (i < m_xDrawable.size())
			{
				m_xDrawable.insert(m_xDrawable.begin() + i, drawable);
				return;
			}
			else
			{
				m_xDrawable.push_back(drawable);
				return;
			}
		}
	}

	m_xDrawable.push_back(drawable);
}

void DisplayManager::Cleanup()
{
	for (unsigned int i = 0; i < m_xDrawable.size(); i++)
	{
		delete m_xDrawable[i].m_xSprite;
		m_xDrawable[i].m_xSprite = nullptr;
	}
	m_xDrawable.clear();
}

void DisplayManager::Draw()
{
	{
		m_xWindow->clear();
		for (unsigned int i = 0; i < m_xDrawable.size(); i++)
		{
			m_xWindow->draw(*m_xDrawable[i].m_xSprite);
		}
		m_xWindow->display();
	}

}

void DisplayManager::DeleteDrawable(sf::Drawable* s_Drawable)
{
	for (unsigned int i = 0; i < m_xDrawable.size(); i++)
	{
		if (m_xDrawable[i].m_xSprite == s_Drawable)
		{
			delete m_xDrawable[i].m_xSprite;
			m_xDrawable.erase(m_xDrawable.begin() + i);
			return;
		}
	}
}